import React, { useRef } from 'react';
import HgBreadCrumb from '../../../components/HgBreadCrumb';
import { Button ,notification } from 'antd';
import "./index.scss"

//注意: 下载xlsx包时 下载最新版
//导入xlsx导入
import * as XLSX from 'xlsx'
//导入file-saver
import fs from 'file-saver'

const Excel = () => {
    
    var inpputRef:any = useRef();

    //解析文件内容并渲染文件内容
    var httpRequest = (file:any) => {
        const types = file.name.split('.')[1]
        const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt'].some(
          (item) => item === types
        )
        if (!fileType) {
          notification.error({message:'格式错误！请重新选择'});
          return
        }
      
        // 方式1（官网推荐、如果有报错就使用方式2）：
        file.arrayBuffer().then((ab:any) => {
          /* Parse file */
          const wb = XLSX.read(ab);
          const ws = wb.Sheets[wb.SheetNames[0]];
      
          /* Generate HTML */
          var ele:any =  document.getElementById('TableContainer');
          ele.innerHTML = XLSX.utils.sheet_to_html(ws)
        });
      
    }

    // 自动分析dom元素导出excel
    var excelExport = (table:any, filename:any) => {

        // 解析dom元素
        const wb = XLSX.utils.table_to_book(table)
    
        /* Export to file (start a download) */
        const defaultCellStyle = {
            font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
            fill: { fgColor: { rgb: 'FFFFAA00' } },
        }

        const wopts:any = {
            bookType: 'xlsx',
            bookSST: false,
            type: 'binary',
            cellStyle: true,
            defaultCellStyle: defaultCellStyle,
            showGridLines: false,
        }

        //生成xlsx格式的数据
        const wbout = XLSX.write(wb, wopts)

        var data:any = [s2ab(wbout)];

        //转换成二进制Blob类型的数据
        const blob = new Blob( data, { type: 'application/octet-stream' })

        //文件另存为
        fs.saveAs(blob, filename+'.xlsx')
    }

    var s2ab = (s:any) => {
        if (typeof ArrayBuffer !== 'undefined') {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
          return buf;
        } else {
          const buf = new Array(s.length);
          for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
          return buf;
        }
    }

    var excelImport = ()=>{
        inpputRef.current.click();
    }
    var handleExcelExport = ()=>{
        var table = document.querySelector('table');
        excelExport(table,'download.xlsx');
    }
    var handleChange = (e:any)=>{
        var file = e.target.files[0];
        httpRequest(file)
    }

    return (
        <div className='excel'>
            <HgBreadCrumb />
            <input type="file" onChange={handleChange} ref={inpputRef} style={{display:'none'}} placeholder='选择一个excel文件' />
            <div className="opts">
                <Button onClick={excelImport}>导入</Button>
                <Button onClick={handleExcelExport}>导出</Button>
            </div>
            <div id="TableContainer"></div>
        </div>
    );
};

export default Excel;